package com.proxy.server.frontend.handler.request.set;

import com.proxy.parser.tree.sql.ast.SQLStatement;
import com.proxy.parser.tree.sql.ast.expr.SQLIntegerExpr;
import com.proxy.parser.tree.sql.ast.expr.SQLVariantRefExpr;
import com.proxy.parser.tree.sql.ast.statement.SQLAssignItem;
import com.proxy.parser.tree.sql.ast.statement.SQLSetStatement;
import com.proxy.common.constant.ErrorCodeType;
import com.proxy.common.packet.BinaryPacket;
import com.proxy.common.packet.ErrorPacket;
import com.proxy.common.packet.OkPacket;
import com.proxy.server.frontend.FrontendConnection;

import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by liufish on 16/8/7.
 */
public class SetAutocommitRequest {



    final static String autocommit = "SET AUTOCOMMIT";

    public static boolean checkAutocommit(String sql) {
        if(sql.toUpperCase().indexOf(autocommit) > -1){
            return true;
        }
        return false;
    }


    public static void doResponse(BinaryPacket bin, FrontendConnection connection, SQLStatement statement, String sql){

        SQLSetStatement sqlSetStatement = (SQLSetStatement)statement;

        List<SQLAssignItem> items = sqlSetStatement.getItems();
        SQLAssignItem item  =  items.get(0);
        SQLVariantRefExpr variantRefExpr = (SQLVariantRefExpr)item.getTarget();
        SQLIntegerExpr integerExpr = (SQLIntegerExpr)item.getValue();

        int i = (int)integerExpr.getValue();
        if(i == 1){
            connection.setAutoCommit(true);
            connection.write(OkPacket.getOk(++bin.packetId));
            return;
        }
        if(i == 0){
            connection.setAutoCommit(false);
            connection.write(OkPacket.getOk(++bin.packetId));
            return;
        }

        ErrorPacket error = new ErrorPacket();
        error.packetId =  ++ bin.packetId;
        error.errNo = ErrorCodeType.ER_NO;
        error.message = "Unknown autocommit!".getBytes(Charset.forName(connection.getCharset()));
        connection.write(error);
    }


}
